package code.remote.request {

import code.Model;
import code.vo.Category;
import code.vo.NeededTopic;
import code.vo.OfferedTopic;

import logging.Logger;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectUtil;
	

public class FetchTopicsRequest extends AbstractRequest {
	
	private static const LOG: Logger = Logger.getLogger("code.remote.request.FetchTopicsRequest");
	
	private static const REQUEST_TYPE: String = "fetch_topics";
	
	private static const MODEL: Model = Model.instance;
	
	public function FetchTopicsRequest() {
		super(REQUEST_TYPE);
	}
	
	protected override function getXmlData(): String {
		return '<Request><User><UserId>' + MODEL.currentUser.userId + '</UserId></User></Request>';
	}
	
	private function clearData(): void {
		for each(var ocat: Category in MODEL.offeredCategories) {
			ocat.topics.removeAll();
		}
		for each(var ncat: Category in MODEL.neededCategories) {
			ncat.topics.removeAll();
		}
	}
	
	protected override function onResult(event: ResultEvent): void {
		const topics: Object = event.result.Topics; 
		
		this.clearData();
		
		const topicsNeeded: Object = topics.NeededTopics;
		if(topicsNeeded == null) {
			// do nothing, empty set
		} else if(topicsNeeded.NeededTopic is ArrayCollection) {
			for each(var ntopic: Object in event.result.Topics.NeededTopics.NeededTopic) {
				MODEL.addNeededTopicByCategory(NeededTopic.newByXml(ntopic));
			}
		} else {
			MODEL.addNeededTopicByCategory(NeededTopic.newByXml(topicsNeeded.NeededTopic));
		}
		
		
		const topicsOffered: Object = topics.OfferedTopics;
		if(topicsOffered == null) {
			// do nothing, empty set
		} else if(topicsOffered.OfferedTopic is ArrayCollection) {
			for each(var otopic: Object in topicsOffered.OfferedTopic) {
				MODEL.addOfferedTopicByCategory(OfferedTopic.newByXml(otopic));
			}
		} else {
			MODEL.addOfferedTopicByCategory(OfferedTopic.newByXml(topicsOffered.OfferedTopic));
			
		}
		
	}
	
	protected override function onFault(event: FaultEvent): void {
		LOG.warning(ObjectUtil.toString(event));
		Alert.show(String(event.fault.message), "Fetch Topics Error");
	}
}
}